package com.zzy.demo.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 
 * @author guokaige
 *
 */
public class JacksonUtil {
	 
	static ObjectMapper mapper = new ObjectMapper();



	/**
	 * 转换json字符串 JSON也是一种序列化。
	 * 
	 * @param object
	 * @return
	 * @throws JsonProcessingException
	 */
	public static String jsonSerialize(Object object) {
		String json = null;
		try {
			json = mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

	/**
	 * 字符串转对象
	 * 
	 * @param object
	 * @param classOfT
	 * @return
	 */
	public static <T> T unJsonSerialize(String json, Class<T> classOfT) {
		T t = null;
		try {
			t = mapper.readValue(json, classOfT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
	
    /**
     * 将json数据转换成pojo对象list
     * @param jsonData  :  String aaa="[{\"num\":\"001\",\"score\":85,\"name\":\"张三\"}]";
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = mapper.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
    }
	
	

	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(String json) {
		Map<String, Object> map = null;
		try {
			map = mapper.readValue(json, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	public static String mapToJson(Map<String, Object> map) {
		String json = null;
		try {
			json = mapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}
	
	
	
	public static void main(String[] args) {
		Map<String, Object>  map=new HashMap<String, Object>();
		map.put("code", "13456");
		map.put("ip", "192.168.1.1");
		System.out.println(mapToJson(map));
	}

}